package com.itheima.reggie.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;

// h5 登录拦截器
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    // jwt权限校验
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.取出请求头
        String token = request.getHeader("Authorization");
        // 非空判断的
        if (StrUtil.isBlank(token)) {
            return loginError(response);
        }
        // 处理Bearer   注意：后面是包括一个空格
        token = token.replace("Bearer ", "");
        // 2.jwt解析token
        Map map = JwtUtil.parseToken(token);
        // 解析失败
        if (map == null) {
            // 没有携带请求头，拦截，返回
            return loginError(response);
        }
        // 3.查询redis中user对象
        String phone = (String) map.get("phone");
        User user = (User) redisTemplate.opsForValue().get("phone:" + phone);
        // 没找到（过期）
        if (user == null) {
            // 没有携带请求头，拦截，返回
            return loginError(response);
        }
        // 4.登录成功了》。。模拟session自动续期
        redisTemplate.expire("phone:" + phone, Duration.ofDays(1));
        // 5.放行
        UserHolder.set(user);
        return true;
    }

    // 登录失败，拦截跳转到登录页面
    private boolean loginError(HttpServletResponse response) throws IOException {
        // 没有携带请求头，拦截，返回
        ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
        // 转json
        String json = JSON.toJSONString(resultInfo); // 阿里巴巴fastJson工具类
        // 响应结果
        response.setContentType("application/json;charset=utf-8"); // MIME类型
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}